package benchmark;

import java.util.ArrayList;

import org.apache.log4j.Logger;

public class Benchmark {
	private static Logger logger = Logger.getLogger(Benchmark.class);
	/*
	 * All time properties in ms.
	 */
	private long startTime;
	private long stopTime;
	private long duration = 60000; // default 1 minute

	
	/*
	 * Parallel clients
	 */
	private int parallelClients = 1;
	private String clientClass = "benchmark.clients.MyCoapClient";
	private ArrayList<ClientRunner> clients = new ArrayList<ClientRunner>();
	
	private RequestCounter counter = new RequestCounter();

	public void setClientClass(String clientClass) {
		this.clientClass = clientClass;
	}
	public static void main(String[] args) {		
		logger.info("Starting Benchmark.");
		
		Benchmark benchmark = null;
		if(args.length > 0)
			benchmark = new Benchmark(args[0]);
		else
			benchmark = new Benchmark();
		benchmark.doBenchmark();
		
		
	}

	public Benchmark()
	{
		this("benchmark.clients.MyCoapClient");
	}

	public Benchmark(String clientClass) {
		if(System.getenv().containsKey("READINGS_DURATION")){
			duration = Long.parseLong(System.getenv().get("READINGS_DURATION"));
		}
		this.clientClass = clientClass;
		if (System.getenv().containsKey("READINGS_PARALLELCLIENTS"))
			parallelClients = Integer.parseInt(System.getenv().get(
					"READINGS_PARALLELCLIENTS"));
		if (System.getenv().containsKey("READINGS_CLIENTCLASS"))
			this.clientClass = System.getenv().get("READINGS_CLIENTCLASS");
		System.out.println("Benchmark runs for " + (duration / 1000)
				+ " seconds using " + parallelClients + " parallel clients.");
		
		System.out.println("Instantiating clients.");
		for(int i=0; i< parallelClients; i++){
			Client client;
			try {
				client = (Client) Class.forName(clientClass).newInstance();
				ClientRunner runner = new ClientRunner(client, counter);
				clients.add(runner);
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
		}
	}

	public void doBenchmark() {
		startTime = System.currentTimeMillis();
		for(Runnable r : clients){
			Thread t = new Thread(r);
			t.start();
		}
		try {
			Thread.sleep(duration);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for(ClientRunner runner : clients){
			runner.stop();
		}
		stopTime = System.currentTimeMillis();
		System.out.println("Requests performed: " + counter.getCount() );
		
	}

}
